package org.example.service.impl;

import lombok.extern.log4j.Log4j2;
import org.example.dao.OrderDao;
import org.example.feign.ProductFeignApi;
import org.example.service.OrderService;
import org.order.pojo.shopOrder;
import org.product.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

@Service
@Log4j2
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ProductFeignApi productFeignApi;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient; //远程调用

    @Override
    @Transactional
    public shopOrder createOrder(Long productId, Long userId) {
        Product product = new Product();
//        ServiceInstance serviceInstance = discoveryClient.getInstances("product-service").get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        String url = "http://product-service/product/getProduct";
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE));
//        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
//        map.add("pid",productId);
//        //组装请求体
//        HttpEntity<MultiValueMap<String, Object>> request =
//                new HttpEntity<MultiValueMap<String, Object>>(map, headers);
//        product = restTemplate.postForObject(url, request, Product.class);
        product.setPid(productId);
        product = productFeignApi.getProduct(product);
        shopOrder shopOrder = new shopOrder();
        shopOrder.setUserId(userId);
        shopOrder.setProductId(productId);
        shopOrder.setProductPrice(product.getPprice());
        shopOrder.setProductNumber(2);
        shopOrder.setOrderId(2l);
        orderDao.save(shopOrder);
        return shopOrder;
    }
}
